import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response, user):
    """
    登录时合并购物车，将cookie中数据合并到redis中
    合并时商品数量和勾选状态以cookie为准
    """
    # 获取cookie中的购物车数据
    cart_cookie = request.COOKIES.get('cart')

    if not cart_cookie:
        return response

    cookie_cart = pickle.loads(base64.b64decode(cart_cookie.encode()))

    redis_conn = get_redis_connection('cart')
    # 获取保存在redis中的数据
    sku_count = redis_conn.hgetall('cart_%s' % user.id)

    # 将字节类型转换成整型
    cart = {}
    for sku_id, count in sku_count.items():
        cart[int(sku_id)] = int(count)

    # 增加勾选的商品id
    redis_selected_add = []
    # 删除没有勾选的商品id
    redis_selected_remove = []

    # 遍历cookie数据
    for sku_id, count_selected in cookie_cart.items():
        cart[sku_id] = count_selected['count']

        if count_selected['selected']:
            redis_selected_add.append(sku_id)
        else:
            redis_selected_remove.append(sku_id)

    # 执行redis
    if cart:
        pl = redis_conn.pipeline()
        pl.hmset('cart_%s' % user.id, cart)
        if redis_selected_add:
            pl.sadd('cart_selected_%s' % user.id, *redis_selected_add)
        if redis_selected_remove:
            pl.srem('cart_selected_%s' % user.id, *redis_selected_remove)
        pl.execute()

    # 删除cookie
    response.delete_cookie('cart')

    return response
















